package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.MyWindowFunction;
import com.atguigu.Util.ClickHouseUtil;
import com.atguigu.Util.DateFormatUtil;
import com.atguigu.Util.MyKafkaUtil;
import com.atguigu.bean.TrafficHomeDetailPageViewBean;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author hjy
 * @create 2023/3/15 16:25
 */
//数据流:web/app -> 日志服务器(file) -> flume -> Kafka(ODS) -> FlinkApp -> Kafka(DWD) -> FlinkApp -> ClickHouse(DWS)
// 程 序:Mock -> file -> f1.sh -> Kafka(ZK) -> BaseLogApp -> Kafka(ZK) -> Dws03_TrafficPageViewWindow -> ClickHouse(ZK)
public class Dws03_TrafficPageViewWindow {
    public static void main(String[] args) throws Exception {
        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall-flink/check");
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HADOOP_USER_NAME", "atguigu");
        //todo 2 从kafka(dwd_traffic_page_log)中读取数据
        String topic = "dwd_traffic_page_log";
        String groupId = "page_view_window";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));
        //todo 3 过滤数据并转为JSON对象并过滤数据 只要page_id为home或者good_detail的数据
        SingleOutputStreamOperator<JSONObject> jsonObjectDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);
                String pageId = jsonObject.getJSONObject("page").getString("page_id");
                if (pageId.equals("home") || pageId.equals("good_detail")) {
                    out.collect(jsonObject);
                }
            }
        });
        //todo 4 提取waterMark时间戳
        SingleOutputStreamOperator<JSONObject> JsonObjWithWMDS = jsonObjectDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("ts");
                    }
                }));
        //todo 5 按照mid分组
        KeyedStream<JSONObject, String> keyedStream = JsonObjWithWMDS.keyBy(value -> value.getJSONObject("common").getString("mid"));

        //todo 6 转为javaBean对象
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> trafficHomeDetailPageViewBeanDS = keyedStream.flatMap(new RichFlatMapFunction<JSONObject, TrafficHomeDetailPageViewBean>() {
            private ValueState<String> homeLastDt;
            private ValueState<String> detailLastDt;

            @Override
            public void open(Configuration parameters) throws Exception {
                homeLastDt = getRuntimeContext().getState(new ValueStateDescriptor<String>("home_last_dt", String.class));
                detailLastDt = getRuntimeContext().getState(new ValueStateDescriptor<String>("detail_last_dt", String.class));
            }

            @Override
            public void flatMap(JSONObject value, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                String pageId = value.getJSONObject("page").getString("page_id");
                Long ts = value.getLong("ts");
                String curtDt = DateFormatUtil.toDate(ts);
                Long homeUv = 0L;
                Long detailUv = 0L;
                if ("home".equals(pageId)) {
                    String lastDt = homeLastDt.value();
                    if (lastDt == null || !lastDt.equals(curtDt)) {
                        homeUv = 1L;
                        homeLastDt.update(curtDt);
                    }
                } else {
                    String lastDt1 = detailLastDt.value();
                    if (lastDt1 == null || !lastDt1.equals(curtDt)) {
                        detailUv = 1L;
                        detailLastDt.update(curtDt);
                    }
                }

                if (homeUv == 1L || detailUv == 1L) {
                    out.collect(new TrafficHomeDetailPageViewBean("",
                            "",
                            homeUv,
                            detailUv,
                            null));
                }

            }
        });
//     有数据   trafficHomeDetailPageViewBeanDS.print("trafficHomeDetailPageViewBeanDS>>>>>>>>>>>>>>>>>>>");
        //todo 开窗聚合
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultDS = trafficHomeDetailPageViewBeanDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean value1, TrafficHomeDetailPageViewBean value2) throws Exception {
                        value1.setHomeUvCt(value1.getHomeUvCt() + value2.getHomeUvCt());
                        value1.setGoodDetailUvCt(value1.getGoodDetailUvCt() + value2.getGoodDetailUvCt());
                        return value1;
                    }
                }, new AllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TrafficHomeDetailPageViewBean> values, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        TrafficHomeDetailPageViewBean next = values.iterator().next();
                        out.collect(MyWindowFunction.getJavabeanFields(next,window));
                    }
                });
        //todo 将数据写出
        resultDS.print("resultDS>>>>>>>>>>>>>>>>>>>>>>");
        resultDS.addSink(ClickHouseUtil.getSinkFunction("insert into dws_traffic_page_view_window values(?,?,?,?,?)"));
        //todo 启动程序
        env.execute();

    }
}
